<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/28
 * Time: 15:31
 */
namespace app\modules\api\models\beauty_cook;
use app\models\ContentComment;
use app\models\User;
use yii\data\Pagination;
use app\modules\api\models\Model;

/**
 * @property ContentComment $model
 * @property $content_id
 * @property $comment
 * @property $type
 * @property $comment_id
 * @property $user_id
 * @property $praise
 */
class ContentCommentForm extends Model{
    public $content_id;
    public $comment;
    public $type;
    public $comment_id;
    public $user_id;
    public $praise;
    public $model;
    public $pages;
    public $pagesize;
    public function rules(){
        return [
            [['content_id','praise',  'type'], 'integer'],
            [['content_id','user_id'],'required'],
            [['comment'],'string'],
        ];
    }
    public function save(){
        if (!$this->validate()) {
            return $this->getModelError();
        }
        $this->model->content_id = $this->content_id;
        $this->model->comment_id = $this->comment_id;
        $this->model->comment = $this->comment;
        $this->model->user_id = $this->user_id;
        $this->model->type = $this->type;
        $this->model->praise = $this->praise;
        if($this->model->save()) {
            return [
                'code' => 0,
                'msg' => '保存成功',
            ];
        }
        else
            return $this->getModelError($this->model);

    }
    public function show(){
        $content_id = $this->content_id;
        $sql = ContentComment::find()->alias('c')->leftJoin(['u'=>User::tableName()],'u.id = c.user_id')
            ->select('c.id,c.comment,u.nickname,u.avatar_url')
            ->where(['c.comment_id'=>$content_id,'c.type'=>0]);
        $count = $sql->count();
        $pages = new Pagination(['totalCount'=>$count,'pageSize'=>$this->pagesize]);
        $offset = ($this->pages-1)*$this->pagesize;
        $res =$sql->offset($offset)
            ->limit($this->pagesize)
            ->asArray()->all();
        foreach ($res as $key=>$val){
            $result =ContentComment::find()->alias('c')->leftJoin(['u'=>User::tableName()],'u.id = c.user_id')
                ->select('c.comment,u.nickname,u.avatar_url')
                ->where(['c.comment_id'=>$val['id'],'c.type'=>1])->asArray()->all();
            $res[$key]['reply']=$result;
        }
        return json_encode(['count'=>$count,'data'=>$res]);
    }
}